package ThreadingSafety;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *  CountDownLatch: 具体介绍见 2022/09/25(2)板书.  [有空自己实现以下]
 */
public class TestDemo31 {
    public static void main(String[] args) throws InterruptedException {
        // 10 个选手参加比赛
        CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 创建 10 个线程执行任务.
            Thread t = new Thread(() -> {

                System.out.println(Thread.currentThread().getName() + "选手出发!");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "选手撞线!");
                // 类似跑步比赛的 撞线.
                countDownLatch.countDown();
            });
            t.start();
        }
        // await 会阻塞等待 直到所有的 "选手" 都 "撞线" 才解除阻塞
        countDownLatch.await();
        //countDownLatch.await(1, TimeUnit.SECONDS); // 可以指定超时时间.
        System.out.println("比赛结束");
    }
}
